<template>
  <div class="container">
    <el-tabs v-model="activeName2" type="card" @tab-click="handleClick">
      <el-tab-pane label="基础信息" name="first">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="班级类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择" @change="Monitor">
              <el-option label="大班" value="1"></el-option>
              <el-option label="中班" value="2"></el-option>
              <el-option label="小班" value="3"></el-option>
              <el-option label="混龄班" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="name" style="width:23%">
            <el-input v-model="ruleForm.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="班主任" prop="organizationUserId">
            <el-select v-model="ruleForm.organizationUserId" placeholder="请选择">
              <el-option v-for="item in organizationArr" :key="item.organizationUserId" :label="item.name" :value="item.organizationUserId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary"  @click="submitForm('ruleForm') ">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="班级学员" name="second">
        <div class="">
          <div class="handle-box">
            <el-button type="primary" @click="showDialog" style="padding: 9px 10px;margin-bottom:5px;font-size: 12px">添加学员</el-button>
          </div>
          <el-dialog title="添加学员" :visible.sync="dialogVisible" width="45%" :before-close="handleClose">
            <el-transfer filterable :titles="['待选择','已选择']" :filter-method="filterMethod" v-model="StudentListData" :data="userArr" class="Alert_K">
            </el-transfer>
            <span slot="footer" class="dialog-footer" style="">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleAddStudent">确认添加</el-button>
            </span>
          </el-dialog>
          <el-table :data="StudenTabData" id="out-table" border style="width: 100%">
            <el-table-column prop="studentId" label="学号"></el-table-column>
            <el-table-column prop="studentName" label="姓名"></el-table-column>
            <el-table-column prop="studentType" :formatter="stateFormat" label="学员类型"></el-table-column>
            <el-table-column prop="goodsName" label="购课套餐"></el-table-column>
            <el-table-column prop="totalPeriods" label="剩余课时">
                  <template slot-scope="scope">
                    <span>{{scope.row.usePeriods}}</span> / <span>{{scope.row.totalPeriods}}</span>
                  </template>
            </el-table-column>
            <el-table-column prop="correctionTime" label="转正时间"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="Studentdelete(scope.row)" size="medium">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="排课计划" name="third">
        <p v-if="status == 0"><a href="javascript:(0)" @click="RowcourseAdmin">当前班级暂无排课，去排课</a></p>
        <ele-calendar v-else :render-content="renderContent" :data="datedef" :prop="prop" value-format="yyyy-MM-dd"></ele-calendar>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import eleCalendar from 'ele-calendar'
import 'ele-calendar/dist/vue-calendar.css'
export default {
  components:{
    eleCalendar
  },
  inject:['reload'],
  data() {
    return {
      userArr: [],
      StudentListData: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
      url: "",
      StudenTabData: [],
      studentList: [],
      ListData: [], //学院列表数据
      editData:{studentIdList:[]},
      pageData: undefined,
      total: 0,
      fengye: 1,
      dialogVisible: false,
      isEnableArr: "",
      activeName2: "first",
      ruleForm: {
        name: "",
        type: "",
        organizationUserId: ""
      },
      rules: {
        name: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择班级类型", trigger: "change" }],
        organizationUserId: [{ required: true, message: "请选择班主任", trigger: "change" }]
      },
      //班主任数据
      organizationArr: {
        organizationUserId: "",
        name: ""
      },
      datedef:[],
      prop:'date',
      nowDate:'',
      teacherInfo:[],
      classInfo:[],
      temp:[],
      status:this.$route.query.status,
      teachClassId:this.$route.query.teachClassId,
      name:this.$route.query.name,
    };
  },
  computed: {
    data() {
      return this.ListData.filter(d => {
        return d;
      });
    }
  },
  watch:{
    $route(to,from){
        if(to.path == '/home/RowCourse'){
        }
    }
  },
  methods: {
    // 判断 添加学员的 按钮信息
    showDialog() {
      if (this.ruleForm.name == "") {
          this.$message({
            showClose: true,
            message: "请先填写相应的班级基础信息~~",
            type: "warning"
          });
      }else{
        this.dialogVisible = true;
      }
    },
    // 创建班级信息，班级名称联动
    Monitor(value){
      this.url = "/api/user/xzs/teachClass.count.get";
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.$axios({
        url:this.url,
        method:"post",
        data:{
          organizationId:organizationId,
          type:value,
        },
        transformRequest: [
              function(data) {
                let ret = "";
                for (let it in data) {
                  ret +=
                    encodeURIComponent(it) +
                    "=" +
                    encodeURIComponent(data[it]) +
                    "&";
                }
                return ret;
              }
            ]
      }).then(res=>{
        console.log(res);
        this.typeData = res.data.data +1
       
        if(value == "1"){
          this.ruleForm.name = "松果"+ this.typeData + "班"
        }else if(value == "2"){
          this.ruleForm.name = "橡果"+ this.typeData + "班"
        }else if(value == "3"){
          this.ruleForm.name = "榛果"+ this.typeData + "班"
        }else if(value == "4"){
          this.ruleForm.name = "果果"+ this.typeData + "班"
        }
      })
    },
    //状态码判断
    stateFormat(row, studentType) {
      if (row.studentType === 2) {
        return "试听";
      } else if (row.studentType === 1) {
        return "正式";
      }
    },
    // 取消创建班级
    cancel(){
      this.$router.push({ path: "/ClassAdmin" });
    },
    //基础信息创建班级
    submitForm(formName) {
      this.activeName2 = "second";
      var that = this;
      this.url = "/api/user/xzs/teachClass.info.save";
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$axios({
            url: this.url,
            method: "post",
            data: {
              name: that.ruleForm.name,
              organizationId: organizationId,
              teachClassId:this.teachClassId?this.teachClassId:'',
              type: that.ruleForm.type,
              organizationUserId: that.ruleForm.organizationUserId
            },
            transformRequest: [
              function(data) {
                let ret = "";
                for (let it in data) {
                  ret +=
                    encodeURIComponent(it) +
                    "=" +
                    encodeURIComponent(data[it]) +
                    "&";
                }
                return ret;
              }
            ]
          }).then(res => {
              this.$message({
                showClose: true,
                message: typeof that.teachClassId !== "undefined" ? "更新成功":"添加成功",
                type: "success"
              });
              this.teachClassId = res.data.data.id
            })
            .catch(err => {
            });
        }
      });
    },
    //编辑班级信息
    EditClass(){
      this.activeName2 = "first";
      var that = this;
      this.url = "/api/user/xzs/teachClass.info.get"; 
      this.$axios({
        url:this.url,
        method:"post",
        data:{  
          teachClassId :that.teachClassId,
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }     
        ]
      }).then(res =>{
        this.editData=res.data.data;
        this.ruleForm ={
          type:String(this.editData.type),
          name:this.editData.name,
          organizationUserId:this.editData.organizationUserId
        }
      }).catch(err =>{
        
      })
    },
    // 添加学员后台数据
    studentListAjax() {
      this.userArr = []
      var that = this;
      this.url = "/api/user/xzs/student.list.get";
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          organizationId:organizationId,
          type: "1"
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }
        ],
      })
        .then(res => {
          this.ListData = res.data.data.pageList;
          this.ListData.forEach((city, index) => {
              this.userArr.push({
                label: city.studentName,
                key: city.studentId,
                pinyin: "lisi"
              });
          });
        })
        .catch(err => {
        });
    },
    // 创建课表
    RowcourseAdmin() {
        if (this.ruleForm.name == "") {
            this.$message({
              showClose: true,
              message: "请先填写相应的班级基础信息~~",
              type: "warning"
            });
        }else{      
          this.$router.push({ path: "/home/RowCourse?id="+this.teachClassId+"&name="+this.ruleForm.name+"&teacherId="+this.ruleForm.organizationUserId+"&status="+0});
      }
    },
    // 分页导航
    handleCurrentChange(val) {  
      this.fengye = val;
    },
    // tab选项
    handleClick(tab, event) {
    },
    // 获取班级学员列表后台数据
    teachClassInfo() {
      var that = this;
      this.url = "/api/user/xzs/teachClass.studentList.get";
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          // teachClassId: "3"
           teachClassId: this.teachClassId || ''
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ],
      })
        .then(res => {
          this.StudenTabData = res.data.data;
          this.StudenTabData.map(function(item) {
            item.correctionTime = that.timestampToTime(item.correctionTime);
          });
        })
        .catch(err => {
        });
    },
    //时间戳转换
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =  (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var m = String(date.getMinutes()).padStart(2, "0");
      return Y + M + D + h + m;
    },
    handleClose() {},
    // 删除学员信息操作
    Studentdelete(row) {
      this.$confirm("此操作将永久删除该学员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          (this.url = "/api/user/xzs/teachClass.student.delete"),
            this.$axios({
              url: this.url,
              method: "post",
              data: {
                teachClassId: this.teachClassId?this.teachClassId:'',
                studentId: row.studentId
              },
              transformRequest: [
                function(data) {
                  let ret = "";
                  for (let it in data) {
                    ret +=
                      encodeURIComponent(it) +
                      "=" +
                      encodeURIComponent(data[it]) +
                      "&";
                  }
                  return ret;
                }
              ],
            })
              .then(res => {
                this.teachClassInfo()
              })
              .catch(err => {
              });
              this.$message({
                type: "success",
                message: "删除成功!"
              });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 添加学员
    handleAddStudent(){
      if(this.StudentListData && this.StudentListData.length > 0){
        this.StudentListData.forEach(item =>{
          if(this.editData && this.editData.studentIdList && this.editData.studentIdList.indexOf(item) > -1){
            this.$message.warning('请不要重复添加学员')
            return
          }
        })
        const data ={
          teachClassId:this.$route.query.teachClassId || this.teachClassId,
          studentIds:this.StudentListData
        }
        this.$axios({
          url:"/api/user/xzs/teachClass.student.add",
          method:'post',
          data
        }).then(res =>{
          this.teachClassInfo()
          this.dialogVisible = false
          this.StudentListData =[]
        }).catch(error =>{

        })
      }else{
        this.$message.warning('请选择学员')
      }
    },
    // 渲染日历上的备注
    renderContent(h,parmas) {
      const loop = data =>{
        return (
          data.defvalue.value ? 
          (<el-tooltip class="item" placement="top" effect="dark" placement="top-start">
              <div slot="content">
                {data.defvalue.value.content1}<br/>
                {data.defvalue.value.content2}<br/>
                {"班级名称："+this.name}
                </div>
              <div>
                  <div>{data.defvalue.text}</div>
                  <span style="line-height:16px;display:inline-block;color:#FFB080;" class="content">
                    {data.defvalue.value.content}
                  </span>
              </div>
            </el-tooltip>) : <div>{data.defvalue.text}</div>)
      }
      return (
      <div style="min-height:60px" >
        {loop(parmas)}
      </div>
      );
    },
     // 获取班级排课信息
      getClassLession(){
          this.$axios({
              url:'/api/course/xzs/lessionPlan.detail.info.get',
              method:'post',
              data:{
              teachClassId:Number(this.teachClassId)
              },
              transformRequest: [
              function(data) {
                  let ret = "";
                  for (let it in data) {
                  ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
                  }
                  return ret;
              }     
              ],
          }).then(res =>{
              if(res.data.value=='成功'){
                  const d = res.data.data.unitList
                  this.temp = []
                  if(d && d.length > 0){
                      d.forEach(item =>{
                        this.temp = this.temp.concat(item.relUnitLessionList)
                      })
                      this.renderInfo()
                  }
                  
              }
          })
      },
      // 渲染数据
      renderInfo(){
        
        var _this = this
        this.temp.forEach((item,index) =>{
          // console.log(item);
          const date =this.timestampToTime(item.beginTime).split(' ')[0]
          const content = item.lessionName
          this.selectChanelAjax(item.organizationUserId,index) 
          this.getData(item.classroomId,index)
          // console.log(item);
            this.$nextTick(() =>{
              this.teacherInfo.push('')
              this.classInfo.push('')
              setTimeout(function(){
                _this.datedef.push(
                  {
                    "date":date,
                    "content":content,
                    "content1":
                        '课程名称：'+item.lessionName,
                    "content2":
                          '教师：'+ _this.teacherInfo[index]
                  }
                )
              },1000)
            })
        })
      },
       // 获取教师列表
      selectChanelAjax(id,index) {
        this.url = "/api/user/xzs/organizationUser.list.get";
        let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
        this.$axios({
          url:this.url,
          method:"post",
          data:{
            organizationId:organizationId,
          },
          transformRequest: [
            function(data) {
              let ret = "";
              for (let it in data) {
                ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
              }
              return ret;
            }     
          ],
        }).then(res => {
            this.organizationArr = res.data.data;
            // console.log(this.organizationArr);
            this.$nextTick(() =>{
              this.organizationArr.forEach(item =>{

                if(item.organizationUserId == id){
                  this.$set(this.teacherInfo,index,item.name)
                }
              })
            })
          });
      },
      // 获取教室列表
      getData(id,index) {
        var that = this;
        let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
        this.url = "/api/user/xzs/teachClass.list.get"; 
        this.$axios({
          url:this.url,
          method:"post",
          data:{
            organizationId:organizationId,
          },
          transformRequest: [
            function(data) {
              let ret = "";
              for (let it in data) {
                ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
              }
              return ret;
            }     
          ],
        }).then(res =>{
          const tableData=res.data.data.pageList
          // console.log(tableData)
          this.$nextTick(() =>{
            tableData.forEach(item =>{
              // console.log(item,id)
              if(item.teachClassId == id){
                this.$set(this.classInfo,index,item.name)
              }
            })
          })
        }).catch(err =>{
      })
    },
    handleClose(done) {
      done();
    }
  },
  mounted() {
    this.teachClassId = this.$route.query.teachClassId
    this.name = this.$route.query.name
    this.teachClassInfo();
    this.selectChanelAjax();
    this.studentListAjax();
    this.getClassLession();
    this.EditClass();
    if(this.$route.query.active){
      const active = this.$route.query.active
      this.activeName2 = active
      if(active == 'second'){
        this.dialogVisible = true
      }
    }
  },
};
</script>

<style>
.handle-box {
  margin-bottom: 20px;
  padding-top: 40px;
  padding-left: 10px;
  height: 50px;
  margin-top: -20px;
  border-radius: 5px;
  background: #f4fafa;
}
.el-tooltip__popper.is-dark{
  line-height: 20px;
}
.item{
  word-break: break-all;
}
.Alert_K{
  float: left;
    width: 100%;
  display: block;
}
.el-transfer__buttons{
  float: left;
  margin-top: 15vh;
}
.el-transfer-panel{
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    display: inline-block;
    vertical-align: middle;
    float: left;
    width: 35%;
    box-sizing: border-box;
}
</style>
